package com.item.action;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;






import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ListObjectsRequest;
import com.aliyun.openservices.oss.model.OSSObjectSummary;
import com.aliyun.openservices.oss.model.ObjectListing;
import com.base.Page;
import com.base.dialect.PaginationSupport;
import com.base.util.DateUtil;
import com.base.util.FileExportUtils;
import com.item.dao.model.EssenceAuthor;
import com.item.dao.model.EssenceAuthorExample;
import com.item.dao.model.EssenceAuthorLockExample;
import com.item.dao.model.EssenceCourse;
import com.item.dao.model.EssenceCourseExample;
import com.item.dao.model.EssenceNew;
import com.item.dao.model.EssenceNewExample;
import com.item.dao.model.Unread;
import com.item.dao.model.UnreadExample;
import com.item.dao.model.User;
import com.item.dao.model.UserExample;
import com.item.dao.model.EssenceNewExample.Criteria;
import com.item.dao.model.EssenceReadState;
import com.item.dao.model.EssenceReadStateExample;
import com.item.dao.model.MediaFile;
import com.item.dao.model.MediaFileExample;
import com.item.exception.JSONRepUtils;
import com.item.service.EssenceAuthorLockService;
import com.item.service.EssenceAuthorService;
import com.item.service.EssenceCourseService;
import com.item.service.EssenceNewService;
import com.item.service.EssenceReadStateService;
import com.item.service.MediaFileService;
import com.item.service.UnreadService;
import com.item.service.UserService;
import com.item.util.ConstantResources;
import com.item.util.MyOssClient;
import com.item.util.SubjectUtils;
@Controller
public class EssenceController {
	
	@Autowired
	private EssenceNewService  essenceService;
	
	@Autowired
	private EssenceAuthorService  authorService;
	
	@Autowired
	private MediaFileService fser;
	
	@Autowired
	private EssenceReadStateService readService;
	
	@Autowired
	private EssenceAuthorLockService lockService;
	
	@Autowired
	private UserService userService;
	@Autowired
	private UnreadService unreadService;
	
	
	
	@RequestMapping("/listEssence")
	@ResponseBody
	public String list(Page param,EssenceNew essence) throws Exception{
		EssenceNewExample example = new EssenceNewExample();
		PaginationSupport.setContext(param.getPageStart(), param.getPageSize(), null);
		Criteria criteria = example.createCriteria();
		
		//以下两个字段用来做筛选  分别是title和source的模糊匹配
		if(StringUtils.isNotBlank(essence.getTitle())){
			criteria.andTitleLike("%"+essence.getTitle()+"%");
		}
		if(StringUtils.isNotBlank(essence.getAuthor())){
			criteria.andAuthorEqualTo(essence.getAuthor());
		}
		if(essence.getSubType() != null){
			criteria.andSubTypeEqualTo(essence.getSubType());
		}
		if(essence.getIsLocked() != null){
			criteria.andIsLockedEqualTo(essence.getIsLocked());
		}
		if(essence.getIsOver() != null){
			criteria.andIsOverEqualTo(essence.getIsOver());
		}
		example.setOrderByClause("author ASC,is_over DESC,top DESC,create_time DESC");
		List<EssenceNew> list = essenceService.selectByExample(example);
		for(EssenceNew item : list){
			item.setAuthor(authorService.selectByPrimaryKey(item.getAuthor()).getName());
		}
		return JSONRepUtils.serialize(new Page(PaginationSupport.getContext().getTotalCount(), list), 0);
	}
	
	@RequestMapping("/showlistEssence")
	public String list() {
		return "essence/essenceList";
	}
	
	@RequestMapping("/toEditEssence")
	public String toEdit()throws Exception{
		return "/essence/essenceEdit";
	}
	
	@RequestMapping(value="/saveEssence",method=RequestMethod.POST)
	@ResponseBody
	public String save(EssenceNew essence, HttpSession session)throws Exception{
		try{
			if(StringUtils.isBlank(essence.getId())){
			}else{
				essence.setModifyTime(new Date());
				essenceService.updateByPrimaryKeySelective(essence);
			}
		}catch(Exception e){
			e.printStackTrace();
			return "{\"success\":false}";
		}
		
		return "{\"success\":true}";
	}
	
	@RequestMapping(value="/findByIdEssence")
	@ResponseBody
	public String findById(String id,HttpSession session)throws Exception{		
		EssenceNew n = essenceService.selectByPrimaryKey(id);
		return JSONRepUtils.serialize(n, 0);
	}
	
	/**
	 * type为0表示只删除条目，为1表示连文件一起删除
	 * @param id
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delEssence")
	@ResponseBody
	public String del(String id,Integer type)throws Exception{
		return delete(id, type);
	}
	
	public String delete(String id, Integer type){
		try{
			String[] ids = id.split(",");
			int len = ids.length;
			for(int i = 0; i < len; i++) {
				essenceService.deleteByPrimaryKey(ids[i]);
				//再删除未读列表中的记录
				EssenceReadStateExample readex = new EssenceReadStateExample();
				readex.createCriteria().andEssenceIdEqualTo(ids[i]);
				readService.deleteByExample(readex);
				//再删除文件列表中的项
				MediaFileExample mfex = new MediaFileExample();
				mfex.createCriteria().andEssenceIdEqualTo(ids[i]);
				//如果是彻底删除的话则把object也删除掉
				if(type == 1){
					List<MediaFile> files = fser.selectByExample(mfex);
					if(files.size() > 0){
						Matcher mat = Pattern.compile("(.*/).*").matcher(files.get(0).getFilePath());
						if(mat.find()){
							for(MediaFile file : files){
								fser.deleteByPrimaryKey(file.getFileId());
								MyOssClient.deleteObject(file.getFilePath(), ConstantResources.BUCKET_NAME_WEBFILE);
							}
							String path = mat.group(1);
							MyOssClient.deleteObject(path, ConstantResources.BUCKET_NAME_WEBFILE);
						}
					}
				}else{
					fser.deleteByExample(mfex);
				}
			}
		}catch(Exception e){
			return "{\"success\":false}";
		}
		return "{\"success\":true}";
	}
	
	@RequestMapping("/moveUpEssence")
	@ResponseBody
	public String moveUp(String id,HttpSession session) throws Exception {
		return processMove(id, 0);
	}
	
	@RequestMapping("/moveDownEssence")
	@ResponseBody
	public String moveDown(String id,HttpSession session) throws Exception {
		return processMove(id, 1);
	}
	
	/**
	 * 操作上移下移的动作
	 * @param uid
	 * @param type
	 * @return
	 */
	public String processMove(String uid,int type){
		EssenceNew now = essenceService.selectByPrimaryKey(uid);
		if(now == null){
			return "{\"success\":false}";
		}
		EssenceNewExample sdex = new EssenceNewExample();
		if(type == 0){
			sdex.createCriteria().andAuthorEqualTo(now.getAuthor()).andTopGreaterThan(now.getTop());
			sdex.setOrderByClause("top ASC");
		}else{
			sdex.createCriteria().andAuthorEqualTo(now.getAuthor()).andTopLessThan(now.getTop());
			sdex.setOrderByClause("top DESC");
		}
		PaginationSupport.setContext(1, 1, null);
		List<EssenceNew> nexts = essenceService.selectByExample(sdex);
		if(nexts == null || nexts.size() == 0){
			return "{\"success\":false}";
		}
		EssenceNew next = nexts.get(0);
		Integer top = next.getTop();
		next.setTop(now.getTop());
		essenceService.updateByPrimaryKeySelective(next);
		now.setTop(top);
		essenceService.updateByPrimaryKeySelective(now);
		return "{\"success\":true}";
	}
	
	@RequestMapping("/cancelEssenceLock")
	@ResponseBody
	public String cancelLock(String id,HttpSession session) throws Exception {
		return updateLock(id,0,0);
	}
	
	@RequestMapping("/addEssenceLock")
	@ResponseBody
	public String addLock(String id,HttpSession session) throws Exception {
		return updateLock(id,1,0);
	}
	
	@RequestMapping("/addEssenceLockAbsolute")
	@ResponseBody
	public String addLockAbsolute(String id,HttpSession session) throws Exception {
		return updateLock(id,1,1);
	}
	
	public String updateLock(String id, int isLocked,int type){
		String result;
		try{
			EssenceNew note = new EssenceNew();
			note.setId(id);
			note.setIsLocked(isLocked);
			essenceService.updateByPrimaryKeySelective(note);
			if(type == 1){
				//这时候是完全加锁，需要把之前用户的分享记录全部删除
				EssenceAuthorLockExample nlex = new EssenceAuthorLockExample();
				nlex.createCriteria().andPidEqualTo(id);
				lockService.deleteByExample(nlex);
			}
			result = "{\"success\":true}";
		}catch(Exception e){
			result = "{\"success\":false}";
		}
		return result;
	}
	
	@RequestMapping("/cancelEssenceOver")
	@ResponseBody
	public String cancelOver(String id,HttpSession session) throws Exception {
		return updateEssenceOver(id,0);
	}
	
	@RequestMapping("/addEssenceOver")
	@ResponseBody
	public String addOver(String id,HttpSession session) throws Exception {
		return updateEssenceOver(id,1);
	}
	
	public String updateEssenceOver(String id, int isOver){
		String result;
		try{
			EssenceNew note = new EssenceNew();
			note.setId(id);
			note.setIsOver(isOver);
			essenceService.updateByPrimaryKeySelective(note);
			result = "{\"success\":true}";
		}catch(Exception e){
			result = "{\"success\":false}";
		}
		return result;
	}
	
	@RequestMapping("/addEssenceNewMessage")
	@ResponseBody
	public String addEssenceNewMessage() throws Exception {
		String result;
		try{
			UnreadExample udex = new UnreadExample();
			Unread read = new Unread();
			read.setModule2(1);
			unreadService.updateByExampleSelective(read, udex);
			result = "{\"success\":true}";
		}catch(Exception e){
			result = "{\"success\":false}";
		}
		return result;
	}
	
	
	@RequestMapping("/updateEssence")
	@ResponseBody
	public String update() throws Exception {
		try{
			MyOssClient os = new MyOssClient();
			OSSClient client = os.getClient();
			for(int i = 1; i < 4 ; i++){
				String initPath = "kaoyanbiji/english/";
				if(i == 2)
					initPath = "kaoyanbiji/policy/";
				else if(i == 3)
					initPath = "kaoyanbiji/math/";
				System.out.println(SubjectUtils.getSubjectByType(i) + "开始*************************");
//				System.out.println(initPath);
				ListObjectsRequest request = new ListObjectsRequest(ConstantResources.BUCKET_NAME_WEBFILE);
				request.setPrefix(initPath);
				request.setDelimiter("/");
				request.setMaxKeys(1000);
				ObjectListing listing = client.listObjects(request);
				for(String common : listing.getCommonPrefixes()){
					//再新建一个rqeust，这是第二级目录
					Matcher mat = null;
					String essenceName = common.split("/")[2];
					if(essenceName.contains("—")){
						mat = Pattern.compile("(.*)（(.*)）—(.*)").matcher("");
					}else{
						mat = Pattern.compile("(.*)（(.*)）-(.*)").matcher("");
					}
					mat.reset(essenceName);
					if(!mat.find()){
						continue;
					}
					String teacher = mat.group(1);
					String depart = mat.group(2);
					String name = mat.group(3);
//					System.out.println(i + "  " + teacher + "  " + depart + "   " + name);
					
					EssenceNewExample eex = new EssenceNewExample();
					eex.createCriteria().andTitleEqualTo(name);
					List<EssenceNew> essences = essenceService.selectByExample(eex);
					EssenceNew essence = null;
					boolean hasEssence = false;
					if(essences != null && essences.size() > 0){
						essence = essences.get(0);
						hasEssence = true;
//						System.out.println("有了 ^^^^   " +name+"  " +teacher);
					}else{
						System.out.println("没有^^^^" +name+"  " +teacher);
						essence = insertNewEssence(name,teacher,i);
						if(essence == null)
							continue;
					}
					//再来遍历该课程下的所有视频文件
					ListObjectsRequest requestThird = new ListObjectsRequest(ConstantResources.BUCKET_NAME_WEBFILE);
					requestThird.setPrefix(common);
					requestThird.setDelimiter("/");
					requestThird.setMaxKeys(1000);
					ObjectListing listingThird = client.listObjects(requestThird);
					//开始的时候首先拿到这个课程下已有的文件
					int newCount = 0;
					final List<OSSObjectSummary> summaries = listingThird.getObjectSummaries();
					for(OSSObjectSummary s : summaries) {
						newCount += updateMediaFile(s,essence);
					}
					//如果是一个已经存在的课程，并且有新的文件加入，那么就去更新状态
					if(hasEssence && newCount > 0){
						EssenceReadStateExample erse = new EssenceReadStateExample();
						erse.createCriteria().andEssenceIdEqualTo(essence.getId());
						EssenceReadState state = new EssenceReadState();
						state.setCount(newCount);
						readService.updateByExampleSelective(state, erse);
					}else if(!hasEssence){
						//再更新大神笔记的未读
						UnreadExample unex = new UnreadExample();
						Unread read = new Unread();
						read.setModule2(1);
						unreadService.updateByExampleSelective(read, unex);
						final EssenceNew temp = essence;
						//为所有的用户添加一条阅读记录
						new Thread(new Runnable() {
							public void run() {
								// TODO Auto-generated method stub
								UserExample uex = new UserExample();
								List<User> users = userService.selectByExample(uex);
								for(User user : users){
									EssenceReadState state = new EssenceReadState();
									state.setAuthorId(temp.getAuthor());
									state.setCount(summaries.size());
									state.setCreateTime(new Date());
									state.setEssenceId(temp.getId());
									state.setUserid(user.getId());
									readService.insert(state);
								}
							}
						}).start();
					}
				}
			}	
			//System.out.println(String.format("name=%s;  mime=%s;  size=%d;  type=%d; path=%s",fileName,mine,s.getSize(),type,s.getKey()));
		}catch(Exception e){
			return "{\"success\":false}";
		}
		return "{\"success\":true}";
	}
	
	public int updateMediaFile(OSSObjectSummary s,EssenceNew essence){
		String[] tmps = s.getKey().split("/");
		String fileName = tmps[tmps.length - 1];
		if(!fileName.contains("."))
			return 0;
		String mine = FileExportUtils.getMine(fileName);
		String fileExt = fileName.substring(
				fileName.lastIndexOf(".") + 1).toLowerCase();
		if(StringUtils.isBlank(fileExt))
			return 0;
		//插入文件
		MediaFileExample mfex = new MediaFileExample();
		int has = 0;
		MediaFile file = null;
		mfex.createCriteria().andFilePathEqualTo(s.getKey());
		List<MediaFile> files = fser.selectByExample(mfex);
		if(files != null && files.size() > 0){
			has = 1;
			file = files.get(0);
		}else{
			file = new MediaFile();
		}
		file.setEssenceId(essence.getId());
		if(has == 0){
			file.setName(fileName.substring(0,
					fileName.lastIndexOf(".")));
		}
		file.setDownloadCount(new Random().nextInt(1000));
		file.setBrowseCount(new Random().nextInt(1000));
		file.setFileBelong("");
		file.setFileCreater("");
		file.setFileCreatetime(new Date());
		file.setFileMd5("");
		file.setFileMinitype(mine);
		file.setFileName(fileName);
		file.setFilePath(s.getKey());
		file.setFileSize(s.getSize());
		file.setFileState(1);
		if(has == 0){
			fser.insert(file);
		}else{
			fser.updateByPrimaryKeySelective(file);
		}
		return has^1;
	}
	
	
	public EssenceNew insertNewEssence(String name,String teacher,int subject){
		EssenceNew essence = new EssenceNew();
		essence.setDate(DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
		essence.setCreateTime(new Date());
		essence.setBrowseTimes(new Random().nextInt(1000));
		essence.setDownloadTimes(new Random().nextInt(1000));
		essence.setIsDigest(1);
		essence.setTop(0);
		essence.setTitle(name);
		essence.setDisplayName(essence.getTitle());
		essence.setType(0);
		essence.setSubType(subject);
		essence.setSource("研大大");
		essence.setHasNew(0);
		essence.setIsOver(0);
		essence.setIsLocked(0);
		essence.setResSize(Long.valueOf("0"));
		//去拿老师的信息
		EssenceAuthorExample desex = new EssenceAuthorExample();
		desex.createCriteria().andNameEqualTo(teacher);
		List<EssenceAuthor> authors = authorService.selectByExample(desex);
		if(authors == null || authors.size() < 1){
			return null;
		}
		EssenceAuthor de = authors.get(0);
		essence.setBelong(de.getBelongid());
		essence.setAuthor(de.getId());
		essence.setCourses("");
		essenceService.insert(essence);
		return essence;
	}
	
	
	
}

